package org.qphoto;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;

public class GifPlayerActivity extends Activity {
	
	ImageView imageView  = null;
	List<String> imglist = new ArrayList<String>();
	Bitmap[] bmpbuffers  = null;
	int      picindex    = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.gifplay);
		
		Bundle bunde    = this.getIntent().getExtras();
	    String imgpath  = bunde.getString("imgpath");
	    int    index    = imgpath.lastIndexOf("/");
	    String fileName = imgpath.substring(index+1);
	    String pathname = imgpath.substring(0,index+1);
		int    findex   = fileName.lastIndexOf("_");
		int    eindex   = fileName.lastIndexOf(".");
		String orgname  = fileName.substring(0,findex+1);
		String ext      = fileName.substring(eindex);
		String numstr   = fileName.substring(fileName.lastIndexOf("_")+1,
				fileName.lastIndexOf("."));
		int    maxnum   = Integer.parseInt( numstr );
		
		imglist.clear();
		bmpbuffers      = new Bitmap[maxnum+1];
		for(int i=0;i<=maxnum;i++)
		{
			bmpbuffers[i] = null;
			imglist.add( pathname + orgname + i + ext);
		}
		
		imageView = (ImageView) this.findViewById(R.id.gifimage);
		imageView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Recylce();
				GifPlayerActivity.this.finish();
			}});
		
		handler.postDelayed(runnable,100);
	}
	
	Handler handler   = new Handler();
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			picindex++;
			if ( picindex >= bmpbuffers.length)
				picindex = 0;
			
			Bitmap bmp = null;
			if ( bmpbuffers[picindex] != null)
			{
				bmp = bmpbuffers[picindex];
			} else {
				String sampleimagepath = imglist.get(picindex);
				Bitmap picimage        = BitmapFactory.decodeFile(sampleimagepath);
				bmpbuffers[picindex]   = picimage;
				bmp                    = picimage;
			}
			imageView.setImageBitmap(bmp);
			handler.postDelayed(runnable,100);
		}
	};
	
	public void Recylce()
	{
		for(int i=0;i<bmpbuffers.length;i++)
		{
			if ( bmpbuffers[i] != null)
			{
				bmpbuffers[i].recycle();
				bmpbuffers[i]   = null;
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Recylce();
	}
}
